﻿using ImCommon;
using System;
using System.Net.Sockets;

namespace ImServer {
    // 客户端
    class Client: Socket {
        private byte[] mBuffer;             // 数据缓存
        private readonly Server mServer;    // 服务器

        /**
         * 构造方法。
         * @param server            服务器
         * @param socketInformation 套接字信息
         */
        public Client(Server server, SocketInformation socketInformation): 
            base(socketInformation) {
            mBuffer = new byte[Const.BUFFER_SIZE];
            mServer = server;
            base.BeginReceive(mBuffer, 0, Const.BUFFER_SIZE, 0, new AsyncCallback(OnReceive), this);
        }

        /**
         * 接收到数据的响应方法。
         * @param result    数据
         */
        public void OnReceive(IAsyncResult result) {
            // 接收数据
            int read = -1;
            try {
                read = base.EndReceive(result);
            } catch (Exception) {
                return;
            }
            if (read <= 0) {
                return;
            }
 
            // 将数据转换成协议
            ImProtocol pro = ImProtocol.FromBytes(mBuffer);

            // 处理协议
            mServer.OnGetMessageFromClient(pro, this);

            // 开始接收数据
            mBuffer = new byte[Const.BUFFER_SIZE];
            try {
                base.BeginReceive(mBuffer, 0, Const.BUFFER_SIZE, 0, new AsyncCallback(OnReceive), this);
            } catch (Exception) {
            }
        }
    }
}
